package com.example.sandbox_basics;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SandboxBasicsDao extends SQLiteOpenHelper {

	private static SandboxBasicsDao instance;
	
	public static final int DATABASE_VERSION = 1;
	public static final String DATABASE_NAME = "SandboxBasics.db";
	private static final String TEXT_TYPE = " TEXT";
	private static final String COMMA_SEP = ",";

	// @formatter:off
	private static final String SQL_CREATE_PERSONAL_DATA = 
			"CREATE TABLE "
			+ SandboxBasicsContract.PersonalData.TABLE_NAME
			+ " (" 
			+ SandboxBasicsContract.PersonalData._ID + " INTEGER PRIMARY KEY,"
			+ SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_FULLNAME + TEXT_TYPE + COMMA_SEP
			+ SandboxBasicsContract.PersonalData.COLUMN_NAME_PERSONAL_DATA_MAIL + TEXT_TYPE
			+ " )";

	private static final String SQL_DELETE_PERSONAL_DATA = 
			"DROP TABLE IF EXISTS "
			+ SandboxBasicsContract.PersonalData.TABLE_NAME;
	// @formatter:on

	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SQL_CREATE_PERSONAL_DATA);
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// This database is only a cache for online data, so its upgrade policy is
		// to simply to discard the data and start over
		db.execSQL(SQL_DELETE_PERSONAL_DATA);
		onCreate(db);
	}

	public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		onUpgrade(db, oldVersion, newVersion);
	}
	
	private SandboxBasicsDao(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	public static SandboxBasicsDao getInstance(Context context) {
		if (instance == null) {
			instance = new SandboxBasicsDao(context);
		}
		return instance;
	}
}
